<template>
  <div class="manage-user-page">
    <!-- 标题与筛选条件容器：用Flex实现对齐 -->
    <div class="header-container">
      <h2 class="page-title">操作员列表</h2>
      <!-- 顶部筛选条件：移除固定margin-left，由Flex布局控制位置 -->
      <div class="filter-bar">
        <el-input
          v-model="searchQuery.nameVo"
          placeholder="请输入姓名查询"
          style="width: 200px; margin-right: 20px;"
        />
        <el-input
          v-model="searchQuery.phoneVo"
          placeholder="请输入手机号查询"
          style="width: 200px;"
        />
        <el-button 
          type="primary" 
          style="margin-left: 20px;"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button 
          type="primary" 
          style="margin-left: 10px;"
          @click="openAddDialog"
        >
          添加操作员
        </el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="users"
      border
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
    >
      <el-table-column
        prop="operatorId"
        label="编号"
        width="120"
      />
      <el-table-column
        prop="name"
        label="昵称"
        width="120"
      />
      <el-table-column
        prop="loginName"
        label="账号名"
        width="120"
      />
      <el-table-column
        prop="phone"
        label="手机号"
        width="200"
      />
      <el-table-column prop="updateTime" label="创建日期" width="200">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        width="100"
      >
        <template #default="scope">
          <el-switch v-model="scope.row.status" @click="kai(scope.row)"  :active-value="1" :inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
      >
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination" style="margin-top: 15px; text-align: right;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[2,5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 添加操作员模态框 -->
    <el-dialog
      title="添加操作员"
      v-model="addDialogVisible"
      width="600px"
      :before-close="handleAddDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="120px"
        :rules="formRules"
        class="add-form"
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入操作员昵称" />
        </el-form-item>
        <el-form-item label="账号名" prop="loginName">
          <el-input v-model="addForm.loginName" placeholder="请设置登录账号" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="addForm.password" 
            type="password" 
            placeholder="请设置登录密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="请选择角色">
            <el-option 
              v-for="role in roles" 
              :key="role.roleId" 
              :label="role.roleName" 
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleAddDialogClose">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑操作员模态框 -->
    <el-dialog
      title="编辑操作员"
      v-model="editDialogVisible"
      width="600px"
      :before-close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="120px"
        :rules="formRules"
        class="edit-form"
      >
        <el-form-item label="编号" prop="operatorId">
          <el-input v-model="editForm.operatorId" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editForm.name" disabled  />
        </el-form-item>
        <el-form-item label="账号名" prop="loginName">
          <el-input v-model="editForm.loginName" placeholder="请输入操作员账号"  />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="editForm.roleId" placeholder="请选择角色">
            <el-option 
              v-for="role in roles" 
              :key="role.roleId" 
              :label="role.roleName" 
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleEditDialogClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 脚本部分保持不变，无需修改
import { ref, onMounted, reactive } from 'vue';
import httpInstance from '../../utils/http';
import { ElMessage, ElMessageBox } from 'element-plus';

const pageNo = ref(1);
const pageSize = ref(5);
const total = ref(0);
const loading = ref(false);
const users = ref([]);
const roles = ref([]);
const searchQuery = reactive({ nameVo: '', phoneVo: '' });
const addDialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = reactive({ name: '', loginName: '', phone: '', password: '', roleId: '', status: 1 });
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = reactive({ operatorId: '', name: '', loginName: '', phone: '', roleId: '', status: 1 });

const formRules = reactive({
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  roleId: [  
    { required: true, message: '请选择所属角色', trigger: 'change' }
  ]
});

onMounted(() => { 
  getoperatorList();
  getRoles();
});

const getoperatorList = async () => { 
  loading.value = true;
  try {
    const {data:res} = await httpInstance.post(`/eduservice/operator/getOperatorAllPage/${pageNo.value}/${pageSize.value}`, searchQuery);
    users.value = res.data.list.list;
    total.value = res.data.list.total;
  } catch (error) {
    ElMessage.error('获取操作员列表失败');
    users.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const getRoles = async () => {
  try {
    const { data: res } = await httpInstance.get('/eduservice/role/getRoleAll');
    roles.value = res.data.list;
  } catch (error) {
    ElMessage.error('获取角色列表失败');
    console.error('角色列表获取失败:', error);
  }
};

const handleSearch = () => {
  pageNo.value = 1;
  getoperatorList();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getoperatorList();
};

const handleCurrentChange = (val) => {
  pageNo.value = val;
  getoperatorList();
};

const kai = async (row)=>{ 
  try {
    const res = await httpInstance.put(`/eduservice/operator/`, row);
    if (res.data.success) {
      ElMessage.success('状态更新成功');
    } else {
      ElMessage.error('状态更新失败');
    }
  } catch (error) {
    ElMessage.error('状态更新失败');
  }
};

const openAddDialog = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addForm.name = '';
  addForm.loginName = '';
  addForm.phone = '';
  addForm.password = '';
  addForm.roleId = '';
  addForm.status = 1;
  addDialogVisible.value = true;
};

const handleAddDialogClose = () => {
  addDialogVisible.value = false;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};

const submitAddForm = async () => {
  try {
    await addFormRef.value.validate();
    const { data: res } = await httpInstance.post('/eduservice/operator', addForm);
    if (res.success) {
      ElMessage.success('添加操作员成功');
      addDialogVisible.value = false;
      getoperatorList();
    } else {
      ElMessage.error(res.message || '添加失败');
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error('添加失败，请重试');
    }
    console.error('添加失败:', error);
  }
};

const openEditDialog = async (row) => {
  try {
    const { data: res } = await httpInstance.get(`/eduservice/operator/${row.operatorId}`);
    const operator = res.data.Operator;
    editForm.operatorId = operator.operatorId;
    editForm.name = operator.name;
    editForm.loginName = operator.loginName;
    editForm.phone = operator.phone;
    editForm.roleId = operator.roleId;
    editForm.status = operator.status;
    editDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取操作员详情失败');
    console.error('编辑详情获取失败:', error);
  }
};

const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
};

const submitEditForm = async () => {
  try {
    await editFormRef.value.validate();
    const { data: res } = await httpInstance.put('/eduservice/operator', editForm);
    if (res.success) {
      ElMessage.success('编辑操作员成功');
      editDialogVisible.value = false;
      getoperatorList();
    } else {
      ElMessage.error(res.message || '编辑失败');
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error('编辑失败，请重试');
    }
    console.error('编辑失败:', error);
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该操作员吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await httpInstance.delete(`/eduservice/operator/${row.operatorId}`);
      ElMessage.success('删除成功');
      getoperatorList();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const formatDate = (dateStr) => {
  if (!dateStr || typeof dateStr !== 'string') return '';
  return dateStr.replace('T', ' ');
};
</script>

<style scoped>
.manage-user-page {
  padding: 20px;
}

/* 核心：标题与筛选条件的容器，实现横向对齐 */
.header-container {
  display: flex;
  align-items: center; /* 垂直方向居中对齐 */
  justify-content: space-between; /* 标题居左，筛选条件居右 */
  margin-bottom: 20px; /* 与下方表格保持间距 */
}

/* 标题样式：优化字体，与筛选条件视觉协调 */
.page-title {
  font-weight: 700; /* 保持加粗 */
  font-size: 18px; /* 调整字体大小，与筛选栏元素比例协调 */
  color: #333; /* 加深颜色，提升标题辨识度 */
  margin: 0; /* 清除默认margin，避免影响对齐 */
}

/* 筛选栏：保留原有flex，确保内部元素对齐 */
.filter-bar {
  display: flex;
  align-items: center; /* 筛选栏内部元素垂直居中 */
}

.add-form, .edit-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>